<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author YDZ
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'bas:mold:basMoldAddIqty:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="60%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm" />
    <template #footer>
      <BpmButton
        v-model:bpmEntity="record"
        bpmEntityKey="id"
        formKey="ASD_MOLD_USEQTY"
        completeText="提交"
        :loading="loadingRef"
        :auth="'bas:mold:basMoldAddIqty:edit'"
        @complete="handleSubmit"
        @success="handleSuccess"
        @close="closeDrawer"
      />
    </template>
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsBasMoldBasMoldAddIqtyForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import {
    BasMoldAddIqty,
    basMoldAddIqtySave,
    basMoldAddIqtyForm,
  } from '/@/api/bas/mold/basMoldAddIqty';
  import { BpmButton } from '/@/components/Bpm';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('bas.mold.basMoldAddIqty');
  const { showMessage } = useMessage();
  const loadingRef = ref(false);
  const record = ref<BasMoldAddIqty>({} as BasMoldAddIqty);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增使用寿命记录') : t('编辑使用寿命记录'),
  }));

  const checkStatus = ref(false);
  const inputFormSchemas: FormSchema[] = [
    {
      label: t('工装名称'),
      field: 'moldCode',
      fieldLabel: 'basMold.name',
      component: 'ListSelect',
      componentProps: ({ formModel }) => {
        return {
          selectType: 'moldSelect',
          onSelect: async (values) => {
            console.log(values);
            formModel['moldCode'] = values[0].code;
            formModel['lastNum'] = values[0].lastNum;
            formModel['basMold.clsCode'] = values[0].clsCode;
            formModel['basMold.caddcode'] = values[0].caddcode;
            formModel['basMold.basMoldCls.name'] = values[0]['basMoldCls']['name'];
            // console.log(formModel);
          },
        };
      },
      // 如果status为4，则不允许修改
      dynamicDisabled: computed(() => record.value.status == '4'),
      required: true,
    },
    {
      label: t('工装代码'),
      field: 'basMold.caddcode',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      required: true,
      dynamicDisabled: computed(() => checkStatus.value || record.value.status == '4'),
    },
    {
      label: t('工装编码'),
      field: 'moldCode',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      required: true,
      dynamicDisabled: computed(() => checkStatus.value || record.value.status == '4'),
    },
    {
      label: t('工装尾号'),
      field: 'lastNum',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      dynamicDisabled: computed(() => checkStatus.value || record.value.status == '4'),
      // required: true,
    },
    {
      label: t('追加次数'),
      field: 'addQty',
      component: 'Input',
      componentProps: {
        maxlength: 8,
      },
      dynamicDisabled: computed(() => checkStatus.value || record.value.status == '4'),
      rules: [{ required: true }, { pattern: /^\d+$/, message: t('请输入一个正整数') }],
    },
    {
      label: t('备注信息'),
      field: 'remarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
      },
      colProps: { lg: 24, md: 24 },
      dynamicDisabled: computed(() => checkStatus.value || record.value.status == '4'),
    },
    {
      label: t('附件上传'),
      field: 'dataMap',
      component: 'Upload',
      componentProps: {
        loadTime: computed(() => record.value.__t),
        bizKey: computed(() => record.value.id),
        bizType: 'moldAddIqty_file',
        uploadType: 'all',
        maxSize: 100,
      },
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('创建者名称'),
      field: 'createByName',
      component: 'Input',
      componentProps: {
        maxlength: 200,
      },
      ifShow: false,
    },
    {
      label: t('检验状态'),
      field: 'checkResult',
      component: 'Input',
      ifShow: false,
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate, updateSchema }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 24, md: 24 },
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    console.log('registerDrawer', data);

    setDrawerProps({ loading: true });
    await resetFields();
    const res = await basMoldAddIqtyForm(data);
    record.value = (res.basMoldAddIqty || {}) as BasMoldAddIqty;
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    setDrawerProps({ loading: false });
    if (data.checkStatus == '1') {
      checkStatus.value = true;
      console.log('updateSchema');
      updateSchema({
        label: t('检验状态'),
        field: 'checkResult',
        component: 'RadioGroup',
        componentProps: {
          dictType: 'repair_and_keep_status',
          allowClear: true,
        },
        required: true,
        ifShow: true,
      });
    }
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      setDrawerProps({ confirmLoading: true });
      data.bpm = record.value.bpm; // 流程信息
      data.status = record.value.status; // 提交状态
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        id: record.value.id,
      };
      // console.log('submit', params, data, record);
      const res = await basMoldAddIqtySave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }

  async function handleSuccess() {
    emit('success');
  }
</script>
